<template>
  <div class="modal-overlay">
    <div class="modal">
      <div class="modal-header">
        <h2>用户注册</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="formData.username"
            required
            placeholder="请输入用户名"
          />
          <p class="error" v-if="errors.username">{{ errors.username }}</p>
        </div>
        
        <div class="form-group">
          <label for="email">电子邮箱</label>
          <input
            type="email"
            id="email"
            v-model="formData.email"
            required
            placeholder="请输入电子邮箱"
          />
          <p class="error" v-if="errors.email">{{ errors.email }}</p>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input
            type="password"
            id="password"
            v-model="formData.password"
            required
            placeholder="请设置密码"
            minlength="6"
          />
          <p class="error" v-if="errors.password">{{ errors.password }}</p>
        </div>
        
        <div class="form-group">
          <label for="confirm-password">确认密码</label>
          <input
            type="password"
            id="confirm-password"
            v-model="formData.confirmPassword"
            required
            placeholder="请再次输入密码"
            minlength="6"
          />
          <p class="error" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</p>
        </div>
        
        <!-- 新增：年龄输入字段 -->
        <div class="form-group">
          <label for="age">年龄</label>
          <input
            type="number"
            id="age"
            v-model="formData.age"
            required
            placeholder="请输入年龄"
            min="1"
            max="150"
          />
          <p class="error" v-if="errors.age">{{ errors.age }}</p>
        </div>
        
        <!-- 新增：真实姓名输入字段 -->
        <div class="form-group">
          <label for="realName">真实姓名</label>
          <input
            type="text"
            id="realName"
            v-model="formData.realName"
            required
            placeholder="请输入真实姓名"
          />
          <p class="error" v-if="errors.realName">{{ errors.realName }}</p>
        </div>
        
        <!-- 新增：学号输入字段 -->
        <div class="form-group">
          <label for="stuNum">学号</label>
          <input
            type="text"
            id="stuNum"
            v-model="formData.stuNum"
            required
            placeholder="请输入学号"
          />
          <p class="error" v-if="errors.stuNum">{{ errors.stuNum }}</p>
        </div>
        
        <!-- 新增：班级选择字段 -->
        <div class="form-group">
          <label for="className">班级</label>
          <select
            id="className"
            v-model="formData.className"
            required
            placeholder="请选择班级"
          >
            <option value="">请选择班级</option>
            <option value="23软件技术1班">23软件技术1班</option>
            <option value="23软件技术2班">23软件技术2班</option>
            <option value="23网络工程1班">23网络工程1班</option>
          </select>
          <p class="error" v-if="errors.className">{{ errors.className }}</p>
        </div>
        
        <div class="form-actions">
          <button 
            type="submit" 
            class="btn btn-primary" 
            :disabled="isLoading"
          >
            {{ isLoading ? '注册中...' : '注册' }}
          </button>
        </div>
        
        <p class="form-footer">
          已有账号？
          <button class="link-btn" @click="showLoginModal">登录</button>
        </p>
      </form>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useUserStore } from '@/stores/user';
import apiService from '@/services/api';
import md5 from 'js-md5'; 
const store = useUserStore();

const emit = defineEmits(['close', 'register-success','RegLogin']);

// 表单数据模型（所有字段初始值为空）
const formData = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  age: '',
  realName: '',
  stuNum: '',
  className: ''
});

const errors = ref({});
const isLoading = ref(false);

const closeModal = () => {
  emit('close');
};

const showLoginModal = () => {
  emit('RegLogin');
};

const handleSubmit = async () => {
  errors.value = {};
  
  // 验证用户名
  if (!formData.value.username) {
    errors.value.username = '用户名不能为空';
  }
  
  // 验证邮箱
  if (!formData.value.email) {
    errors.value.email = '电子邮箱不能为空';
  } else if (!isValidEmail(formData.value.email)) {
    errors.value.email = '请输入有效的电子邮箱地址';
  }
  
  // 验证密码
  if (!formData.value.password) {
    errors.value.password = '密码不能为空';
  } else if (formData.value.password.length < 6) {
    errors.value.password = '密码长度至少需要6个字符';
  }
  
  // 验证确认密码
  if (!formData.value.confirmPassword) {
    errors.value.confirmPassword = '请确认密码';
  } else if (formData.value.password !== formData.value.confirmPassword) {
    errors.value.confirmPassword = '两次输入的密码不一致';
  }
  
  // 验证新增字段
  if (!formData.value.age) {
    errors.value.age = '年龄不能为空';
  } else if (isNaN(Number(formData.value.age)) || formData.value.age < 1 || formData.value.age > 150) {
    errors.value.age = '请输入有效的年龄（1-150之间）';
  }
  
  if (!formData.value.realName) {
    errors.value.realName = '真实姓名不能为空';
  }
  
  if (!formData.value.stuNum) {
    errors.value.stuNum = '学号不能为空';
  } else if (formData.value.stuNum.length < 6) {
    errors.value.stuNum = '学号长度至少需要6个字符';
  }
  
  if (!formData.value.className) {
    errors.value.className = '请选择班级';
  }
  
  // 如果有错误，不提交
  if (Object.keys(errors.value).length > 0) {
    // 滚动到第一个错误字段
    const firstError = document.querySelector('.error');
    if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
    return;
  }
  
  isLoading.value = true;
  
  try {
    // 提交用户输入的所有数据（无默认值）
    const userData = {
      username: formData.value.username,
      pwd: md5(formData.value.password),
      email: formData.value.email,
      age: formData.value.age,
      realName: formData.value.realName,
      stuNum: formData.value.stuNum,
      className: formData.value.className
    };
    const response = await apiService.register(userData);
    // console.log(response)
    // 注册后自动登录
    // const token = response.token;
    // const user = response.user;
    
    // store.setToken(token);
    // store.setUser(user);
    alert("注册成功，即将跳转登录")
    emit('register-success');
  } catch (error) {
    console.error('注册失败:', error);
    alert('注册失败')
    if (error.response && error.response.data.message) {
      errors.value.general = error.response.data.message;
    } else {
      errors.value.general = '注册失败，请稍后再试。';
    }
  } finally {
    isLoading.value = false;
  }
};

// 邮箱验证函数
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};
</script>

<style scoped>
/* 样式保持不变 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 100%;
  max-width: 400px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.form-group .error {
  color: #e94560;
  font-size: 14px;
  margin-top: 5px;
}

.form-actions {
  margin-top: 20px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
  width: 100%;
}

.btn-primary {
  background-color: #e94560;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.link-btn {
  background: none;
  border: none;
  color: #e94560;
  cursor: pointer;
  font-weight: 500;
  padding: 0;
}

.link-btn:hover {
  text-decoration: underline;
}
</style>